package com.demo.gulimall.auth.component;

import com.aliyun.tea.TeaException;
import com.demo.gulimall.auth.config.MyAliyunSmsConfig;
import com.demo.gulimall.common.utils.R;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author Chen Yuan
 * @create 2023-06-13  16:21
 */
@Data
@Slf4j
@Component
@ConfigurationProperties(prefix = "aliyun.cloud")
public class SmsComponent {

	private String accessKeyId;

	private String accessKeySecret;


	public R sendCode(String phone, String code){
		try {
		com.aliyun.dysmsapi20170525.Client client = MyAliyunSmsConfig.createClient(accessKeyId, accessKeySecret);
		com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
				.setSignName("阿里云短信测试")
				.setTemplateCode("SMS_154950909")
				.setPhoneNumbers(phone)
				.setTemplateParam("{\"code\":\""+code+"\"}");
		com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

			client.sendSmsWithOptions(sendSmsRequest, runtime);
			return R.ok("发送成功");
		} catch (TeaException error) {
			log.error("--> 发送短信验证码异常 - msg:{}", error.message);
			return R.error("发送失败-"+error.message);
		} catch (Exception _error) {
			TeaException error = new TeaException(_error.getMessage(), _error);
			log.error("--> 发送短信验证码异常 - msg:{}", error.message);
			return R.error("发送失败-"+error.message);
		}
	}
}
